package com.whmnx.main.ui;

import android.Manifest;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.widget.RadioGroup;
import android.widget.Toast;

import androidx.core.content.ContextCompat;
import androidx.core.view.GravityCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import androidx.lifecycle.Observer;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.video.player.lib.base.IMediaPlayer;
import com.whmnx.base.bean.PersonalBean;
import com.whmnx.base.constants.Constants;
import com.whmnx.base.constants.EventConstants;
import com.whmnx.base.contract._Login;
import com.whmnx.base.http.CallBack;
import com.whmnx.base.http.HttpClient;
import com.whmnx.base.router.RouterActivityPath;
import com.whmnx.base.router.RouterFragmentPath;
import com.whmnx.base.utils.UItils;
import com.whmnx.main.BR;
import com.whmnx.main.R;
import com.whmnx.main.databinding.ActivityMainBinding;
import com.whmnx.main.ui.model.MainModel;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.annotations.Nullable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import me.goldze.mvvmhabit.base.BaseActivity;
import me.goldze.mvvmhabit.bus.RxBus;
import me.goldze.mvvmhabit.bus.RxSubscriptions;
import me.goldze.mvvmhabit.utils.SPUtils;
import me.majiajie.pagerbottomtabstrip.NavigationController;
import me.majiajie.pagerbottomtabstrip.listener.OnTabItemSelectedListener;

/**
 * author : huang
 * date   : 2020/9/10 0010 10:54
 * version: 1.0
 * @author Administrator
 */
@Route(path = RouterActivityPath.Main.PAGER_MAIN)
public class MainActivity extends BaseActivity<ActivityMainBinding, MainModel> implements RadioGroup.OnCheckedChangeListener {
    private List<Fragment> mFragments;
    Disposable subscribe;

    private RadioGroup mRg_content_fragment;

    private Fragment currentFragment;

    private long exitTime;
    private Map<String, ?> all;

    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_main;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    public void initData() {
        initFragment();
        initView();
        //初始化Fragment
        //初始化底部Button
        initBottomTab();
        viewModel.initToolbar(this);
        initRxPermissions();
        mRg_content_fragment = (RadioGroup) findViewById(R.id.rg_content_fragment);
        mRg_content_fragment.setOnCheckedChangeListener(this);
        replaceFragment("home");
        getUserInfo();
        //晚上12 点之后
        //今天
       String day = UItils.getDayTime2();
        Log.i("main", day + "-----day--------");
      //  String day = "10";
        String yesToday =  SPUtils.getInstance().getString("yesToday");
        Log.i("main", yesToday + "-----yestoday--------");
        if (!TextUtils.isEmpty(yesToday)) {
            if (!day.equals(yesToday)) {
                SPUtils.getInstance().put("today", false);
                SPUtils.getInstance().put("pro", 0);
                all = SPUtils.getInstance().getAll();

                for (String key : all.keySet()) {
                    if (key.contains("progresssss")) {
                        String key1 = key;
                        SPUtils.getInstance().remove(key1);
                    }
                    if (key.contains("progress")) {
                        String key2 = key;
                        SPUtils.getInstance().remove(key2);
                    }
                }
            }
        }
       /* if (UItils.getDay()){
            SPUtils.getInstance().put("today",false);
            SPUtils.getInstance().put("pro", 0);
            all = SPUtils.getInstance().getAll();

            for(String key : all.keySet()){
                if (key.contains("progresssss")){
                    String  key1 = key;
                    SPUtils.getInstance().remove(key1);
                }
                if (key.contains("progress")){
                    String  key2 = key;
                    SPUtils.getInstance().remove(key2);
                }
            }

        }else {
           // SPUtils.getInstance().put("today", true);
        }*/
    }

    private void getUserInfo() {
        Map<String, Object> params = new HashMap<>();
        params.put("uId", SPUtils.getInstance().getString(Constants.USERID));
        HttpClient.get(this, Constants.PERSONALINFORMATION, params,new CallBack<PersonalBean>() {
            @Override
            public void onSuccess(PersonalBean personalBean) {

                SPUtils.getInstance().put(Constants.LV, personalBean.getUserInfo_Lv());

                SPUtils.getInstance().put(Constants.PAYWORD, personalBean.getUserInfo_SafePwd());
                SPUtils.getInstance().put(Constants.NICKNAME, personalBean.getUserInfo_NickName());
            }
        });
    }

    private void initRxPermissions() {
        //    if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
        //                && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        //            return;
        //        }
        //请求打开相机权限
        RxPermissions rxPermissions = new RxPermissions( MainActivity.this);
        rxPermissions.request(Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE
        ,Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.RECORD_AUDIO)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        if (aBoolean) {
//注意6.0及以上版本需要在申请完权限后调用方法
                           /* LocationUtils.getInstance(MainActivity.this).setAddressCallback(new LocationUtils.AddressCallback() {
                                @Override
                                public void onGetAddress(Address address) {
                                    String countryName = address.getCountryName();//国家
                                    String adminArea = address.getAdminArea();//省
                                    String locality = address.getLocality();//市
                                    String subLocality = address.getSubLocality();//区
                                    String featureName = address.getFeatureName();//街道
                                    Log.i("base",countryName + adminArea + locality + subLocality + featureName);
                                }

                                @Override
                                public void onGetLocation(double lat, double lng) {
                                    //  LogUtils.eTag("定位经纬度",lat,lng);
                                }
                            });*/
                        } else {

                        }
                    }
                });
    }

    @Override
    public void initViewObservable() {
        //监听ViewModel中pSwitchObservable的变化, 当ViewModel中执行【uc.pSwitchObservable.set(!uc.pSwitchObservable.get());】时会回调该方法
        viewModel.uc.pSwitchEvent.observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(@Nullable Boolean aBoolean) {
                //pSwitchObservable是boolean类型的观察者,所以可以直接使用它的值改变密码开关的图标
                if (viewModel.uc.pSwitchEvent.getValue()) {
                    binding.drawerLayout.openDrawer(GravityCompat.START);
                }else {
                    binding.drawerLayout.closeDrawer(GravityCompat.START);
                }
            }
        });
    }

    private void initView() {
         subscribe = RxBus.getDefault().toObservable(Object.class)
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object object){
                        if (_Login.class.isInstance(object)){
                            finish();
                        }else if (object.equals(EventConstants.LEFT)){
                            binding.drawerLayout.openDrawer(GravityCompat.START);
                        }
                    }
                });
        RxSubscriptions.add(subscribe);
    }


    private void initFragment() {
        //ARouter拿到多Fragment(这里需要通过ARouter获取，不能直接new,因为在组件独立运行时，宿主app是没有依赖其他组件，所以new不到其他组件的Fragment)
        Fragment homeFragment = (Fragment) ARouter.getInstance().build(RouterFragmentPath.Home.PAGER_HOME).navigation();
        Fragment workFragment = (Fragment) ARouter.getInstance().build(RouterFragmentPath.City.PAGER_WORK).navigation();
        Fragment msgFragment2 = (Fragment) ARouter.getInstance().build(RouterFragmentPath.City.PAGER_WORK).navigation();
        Fragment msgFragment = (Fragment) ARouter.getInstance().build(RouterFragmentPath.Shop.PAGER_MSG).navigation();
        Fragment meFragment = (Fragment) ARouter.getInstance().build(RouterFragmentPath.User.PAGER_ME).navigation();
        mFragments = new ArrayList<>();
        mFragments.add(homeFragment);
        mFragments.add(workFragment);
        mFragments.add(msgFragment2);
        mFragments.add(msgFragment);
        mFragments.add(meFragment);
       /* if (homeFragment != null) {
            //默认选中第一个
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
            transaction.add(R.id.frameLayout, homeFragment);
            transaction.commitAllowingStateLoss();
        }*/
    }

    private void initBottomTab() {
        NavigationController navigationController = binding.pagerBottomTab.material()
                .addItem(R.mipmap.shouye, "首页")
                .addItem(R.mipmap.city, "同城")
                .addItem(R.color.white,null)
                .addItem(R.mipmap.gouwuche, "购物车")
                .addItem(R.mipmap.wode, "我的")
                .setDefaultColor(ContextCompat.getColor(this, R.color.textColorGray))
                .build();
        //底部按钮的点击事件监听
        navigationController.addTabItemSelectedListener(new OnTabItemSelectedListener() {
            @Override
            public void onSelected(int index, int old) {
                Fragment currentFragment = mFragments.get(index);
                if (currentFragment != null) {
                    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
                //    transaction.replace(R.id.frameLayout, currentFragment);
                    transaction.commitAllowingStateLoss();
                }
            }

            @Override
            public void onRepeat(int index) {
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //解除注册
         RxSubscriptions.remove(subscribe);
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        int position = group.indexOfChild(group.findViewById(checkedId));
        switch (position){
            case 0:
                replaceFragment("home");
                break;
            case 1:
                replaceFragment("city");
                break;
            case 2:
                replaceFragment("mine");
                break;
            case 3:
                replaceFragment("shop");
                break;
            case 4:
                replaceFragment("my");
                break;
            default:
        }
    }


    private void replaceFragment(String tag) {
        if (currentFragment != null) {
            Log.i("MainActivity", tag + "-----1");
            getSupportFragmentManager().beginTransaction().hide(currentFragment).commit();
        }
        currentFragment = getSupportFragmentManager().findFragmentByTag(tag);
        if (currentFragment == null) {
            switch (tag) {
                case "home":
                    currentFragment = mFragments.get(0);
                    break;
                case "city":
                    currentFragment = mFragments.get(1);
                    break;
                case "mine":
                    currentFragment = mFragments.get(2);
                    break;
                case "shop":
                    currentFragment = mFragments.get(3);
                    break;
                case "my":
                    currentFragment = mFragments.get(4);
                    break;
                default:
            }
            Log.i("MainActivity", tag + "-----2");
            getSupportFragmentManager().beginTransaction().add(R.id.frameLayout, currentFragment, tag).commit();
        } else {
            getSupportFragmentManager().beginTransaction().show(currentFragment).commit();
        }
    }


    @Override
    public void onBackPressed() {
        IMediaPlayer.getInstance().isBackPressed(true);
        if ((System.currentTimeMillis() - exitTime) > 2000) {
            Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
            exitTime = System.currentTimeMillis();
        }
        else{
            finish();
        }
    }
}
